﻿using HiStore.Cache;
using HiStore.Configuration;
using HiStore.Util.Core;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HiStore.Core.Config
{
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlSugarSetup
    {
        public static void AddSqlSugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            string connectionString = AppSettingsConstVars.DbSqlConnection;
            string dbTypeString = AppSettingsConstVars.DbDbType;
            int dbCommandTimeout = AppSettingsConstVars.DBCommandTimeout;
            int SlaveHitRate1= AppSettingsConstVars.SlaveHitRate1;
            int SlaveHitRate2 = AppSettingsConstVars.SlaveHitRate2;
            //获取数据类型
            var dbType = dbTypeString == DbType.MySql.ToString() ? DbType.MySql : DbType.SqlServer;
            //判断是否开启redis设置二级缓存方式
            

            ICacheService myCache =(ICacheService)App.ServiceProvider.GetService<MemoryCacheService>();

            var connectionConfig = new ConnectionConfig()
            {
                ConnectionString = connectionString, //必填
                DbType = dbType, //必填
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                SlaveConnectionConfigs = new List<SlaveConnectionConfig>()
                {
                    new SlaveConnectionConfig() { HitRate = SlaveHitRate1, ConnectionString = AppSettingsConstVars.DbSqlConnection1 },
                    new SlaveConnectionConfig() { HitRate = SlaveHitRate2, ConnectionString = AppSettingsConstVars.DbSqlConnection2 }
                },
                ConfigureExternalServices = new ConfigureExternalServices()
                {
                    DataInfoCacheService = myCache  //配置我们创建的缓存类
                }
            };


            services.AddScoped<ISqlSugarClient>(o =>
            {

                var db = new SqlSugarClient(connectionConfig); //默认SystemTable

                db.Ado.IsDisableMasterSlaveSeparation = true;//读写分离配置,强制走主库

                db.Ado.CommandTimeOut = dbCommandTimeout;//默认连接超时/秒

                db.Aop.OnError = (exp) =>//执行SQL 错误事件
                {
                    
                };
                db.Aop.OnLogExecuting = (sql,pars) => {
                    Console.WriteLine(sql);
                    Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));
                    Console.WriteLine(db.Ado.Connection.ConnectionString);
                };
                return db;
            });

        }
    }
}
